package com.shunhe.shyqfk;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;

import com.ailiwean.core.Result;
import com.google.gson.reflect.TypeToken;
import com.permissionx.guolindev.PermissionX;
import com.permissionx.guolindev.callback.ExplainReasonCallback;
import com.permissionx.guolindev.callback.RequestCallback;
import com.permissionx.guolindev.request.ExplainScope;
import com.ruitu.arad.api.okhttp.Url;
import com.ruitu.arad.api.okhttp.response.JsonResponseHandler;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.arad.util.ViewUtils;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.util.AlertUtil;
import com.shunhe.shyqfk.base.Gl;
import com.shunhe.shyqfk.model.CodeStr;
import com.shunhe.shyqfk.model.EnterQuery;
import com.shunhe.shyqfk.model.OutQuery;
import com.shunhe.shyqfk.model.Partition;
import com.shunhe.shyqfk.support.util.ComUtil;
import com.shunhe.shyqfk.support.view.CusZxingView;
import com.shunhe.shyqfk.ui.PhotoCheckActivity;
import com.shunhe.shyqfk.ui.RegisterCodeActivity;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends BaseActivity {
    CusZxingView cusZxing;
    RelativeLayout rl_content;
    TextView tv_resume, tv_sleep, tv_qrcode, tv_sleep_mask;
    TextView tv_partition, tv_search, tv_search2;
    AppCompatEditText et_word, et_word2;

    private String code;// 扫描出来的二维码结果
    private ArrayList<Partition> partitionList = new ArrayList<>();// 园区列表
    private Partition currPartition;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cusZxing = findViewById(R.id.cusZxing);
        rl_content = findViewById(R.id.rl_content);
        tv_resume = findViewById(R.id.tv_resume);
        tv_sleep = findViewById(R.id.tv_sleep);
        tv_qrcode = findViewById(R.id.tv_qrcode);
        tv_sleep_mask = findViewById(R.id.tv_sleep_mask);
        tv_partition = findViewById(R.id.tv_partition);
        tv_search = findViewById(R.id.tv_search);
        tv_search2 = findViewById(R.id.tv_search2);
        et_word = findViewById(R.id.et_word);
        et_word2 = findViewById(R.id.et_word2);

        setNoNavigationIcon();// 不显示后退按钮

        // 动态设置扫码框大小
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) cusZxing.getLayoutParams();
        int size = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(40);
        params.width = size;
        params.height = (int) (size * 0.618);
        cusZxing.setLayoutParams(params);

        RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) tv_sleep_mask.getLayoutParams();
        params2.width = size;
        params2.height = (int) (size * 0.618);
        tv_sleep_mask.setLayoutParams(params2);

        tv_sleep_mask.setVisibility(View.GONE);

        // 请求相关权限
        PermissionX.init(this)
                .permissions(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onExplainRequestReason(new ExplainReasonCallback() {
                    @Override
                    public void onExplainReason(@androidx.annotation.NonNull ExplainScope scope, @androidx.annotation.NonNull List<String> deniedList) {
                        String message = "需要您允许以下权限才能正常使用";
                        scope.showRequestReasonDialog(deniedList, message, "允许", "拒绝");
                    }
                }).request(new RequestCallback() {
            @Override
            public void onResult(boolean allGranted, @androidx.annotation.NonNull List<String> grantedList, @androidx.annotation.NonNull List<String> deniedList) {
                if (allGranted) {
                    cusZxing.synchLifeStart(MainActivity.this);
                    setListeners();
                    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            cusZxing.cameraPause();
                            tv_sleep_mask.setVisibility(View.VISIBLE);
                        }
                    }, 1000);// 默认关闭扫码功能
                } else {
                    ToastUtils.showLong("相机和文件存储权限被拒绝,功能无法使用");
                }
            }
        });

        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
        alert2 = new AlertDialog.Builder(this, R.style.Dialog_FS).create();

        setOnClickListener(tv_qrcode, tv_partition, tv_search);

        partitionList.add(new Partition("天源国际物流园一期", "1"));
        partitionList.add(new Partition("天源国际物流园二期", "2"));
        partitionList.add(new Partition("天源国际物流园三期", "3"));
        partitionList.add(new Partition("顺和国际智慧物流园", "4"));

        setHeadTitle("疫情防控");
        // VERSION 1 天源 2 顺和国际 3 汪沟镇
        if (Url.VERSION == 1) {
            currPartition = partitionList.get(0);// 天源国际物流园一期
        } else if (Url.VERSION == 2 || Url.VERSION == 4) {
            currPartition = partitionList.get(3);// 顺和国际智慧物流园
        } else if (Url.VERSION == 3) {
            reqParkList();// 汪沟镇
        }

        if (null != currPartition) {
            tv_partition.setText(currPartition.getName());
        }

    }

    private void setListeners() {
        cusZxing.setOnGetScanResultListener(new CusZxingView.OnGetScanResultListener() {
            @Override
            public void onGetScanResult(Result content) {
                // 收到扫码结果
                code = content.getText();
                Logg.i("code = " + code);

                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        cusZxing.cameraResume();// 延迟一段时间,恢复扫码
                    }
                }, 1000);

                String id = "";// 记录出、入园区的登记id
                String type = "";// 出入园区的类型 1 入 2 出
                try {
                    CodeStr codeStr = Gl.gson.fromJson(code, new TypeToken<CodeStr>() {
                    }.getType());
                    id = codeStr.getId();
                    type = codeStr.getType();
                } catch (Exception e) {
                    Logg.i("解析json错误，code = " + code);
                    type = "1";// 解析错误，默认为是入园
                    id = code;// 解析错误，code就是id
                    e.printStackTrace();
                }

                try {
                    int idNum = Integer.parseInt(id);// 尝试解析id为数字
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertUtil.showComDialog2(MainActivity.this, "二维码错误，请出示登记信息码!", null);
                    return;
                }

                if (!TextUtils.isEmpty(id) && id.length() >= 16) {
                    AlertUtil.showComDialog2(MainActivity.this, "二维码错误，请出示登记信息码!", null);
                }

                if (TextUtils.equals("1", type)) {// 查询入园
                    reqEnterQuery(id, "");
                } else {// 查询出园
                    reqOutQuery(id, "");
                }

            }
        });

        setOnClickListener(tv_resume, tv_sleep, tv_search, tv_search2);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_resume) {
            if (null != cusZxing) {
                cusZxing.cameraResume();
                tv_sleep_mask.setVisibility(View.GONE);
            }
        }
        if (v == tv_sleep) {
            if (null != cusZxing) {
                cusZxing.cameraPause();
                tv_sleep_mask.setVisibility(View.VISIBLE);
            }
        }
        if (v == tv_qrcode) {
            startActivity(RegisterCodeActivity.class);
        }
        if (v == tv_partition) {// 切换园区
            ComUtil.showCustomOptionPicker(this, partitionList, "选择园区", new ComUtil.OnSelectListener() {
                @Override
                public void onSelect(int opt1, int opt2, int opt3) {
                    currPartition = partitionList.get(opt1);
                    tv_partition.setText(currPartition.getName());
                }
            });
        }
        if (v == tv_search) {
            String word = ViewUtils.getTvTxt(et_word);
            if (TextUtils.isEmpty(word)) {
                ToastUtils.showShort("请输入关键字!");
                return;
            }
            reqEnterQuery("", word);
        }
        if (v == tv_search2) {
            String word = ViewUtils.getTvTxt(et_word2);
            if (TextUtils.isEmpty(word)) {
                ToastUtils.showShort("请输入关键字!");
                return;
            }
            reqOutQuery("", word);
        }

    }

    // 根据扫码结果请求入入入园登记信息
    private void reqEnterQuery(String id, String word) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id);
        params.put("search", word);

        hideProgress();
        showProgress();
        Gl.okHttp.get().url(Url.ENTER_QUERY).params(params)
                .tag(this).enqueue(this, new JsonResponseHandler() {
            @Override
            public void onFailure(int statusCode, String error_msg) {
                hideProgress();
                ToastUtils.showShort("请求失败");
                Logg.i("reqEnterQuery.error_msg = " + error_msg);
            }

            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                hideProgress();
                String code = response.optString("code");
                String msg = response.optString("msg");
                String data = response.optString("data");
                Logg.i("reqEnterQuery.code = " + code + " msg = " + msg);
                Logg.i("reqEnterQuery.data = " + data);
                if (TextUtils.equals("1", code)) {
                    EnterQuery enter = Gl.gson.fromJson(data, new TypeToken<EnterQuery>() {
                    }.getType());
                    showDialog(enter);
                } else {
                    ToastUtils.showShort(msg);
                    AlertUtil.showComDialog2(MainActivity.this, msg, null);
                }
            }
        });
    }

    // 根据扫码结果请求出出出园登记信息
    private void reqOutQuery(String id, String word) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id);
        params.put("search", word);

        hideProgress();
        showProgress();
        Gl.okHttp.get().url(Url.OUT_QUERY).params(params)
                .tag(this).enqueue(this, new JsonResponseHandler() {
            @Override
            public void onFailure(int statusCode, String error_msg) {
                hideProgress();
                ToastUtils.showShort("请求失败");
                Logg.i("reqOutQuery.error_msg = " + error_msg);
            }

            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                hideProgress();
                String code = response.optString("code");
                String msg = response.optString("msg");
                String data = response.optString("data");
                Logg.i("reqOutQuery.code = " + code + " msg = " + msg);
                Logg.i("reqOutQuery.data = " + data);
                if (TextUtils.equals("1", code)) {
                    OutQuery out = Gl.gson.fromJson(data, new TypeToken<OutQuery>() {
                    }.getType());
                    showDialog2(out);
                } else {
                    ToastUtils.showShort(msg);
                    AlertUtil.showComDialog2(MainActivity.this, msg, null);
                }
            }
        });
    }

    // 确认入入入园信息
    private void reqConfirmEnter(String id) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id);
        params.put("partition", currPartition.getIndex());

        hideProgress();
        showProgress();
        Gl.okHttp.get().url(Url.ENTER_CONFIRM).params(params)
                .tag(this).enqueue(this, new JsonResponseHandler() {
            @Override
            public void onFailure(int statusCode, String error_msg) {
                hideProgress();
                ToastUtils.showShort("请求失败");
                Logg.i("reqConfirmEnter.error_msg = " + error_msg);
            }

            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                hideProgress();
                String code = response.optString("code");
                String msg = response.optString("msg");
                String data = response.optString("data");
                Logg.i("reqConfirmEnter.code = " + code + " msg = " + msg);
                Logg.i("reqConfirmEnter.data = " + data);
                if (TextUtils.equals("1", code)) {
                    AlertUtil.showComDialog2(MainActivity.this, msg, null);
                } else {
                    ToastUtils.showShort(msg);
                    AlertUtil.showComDialog2(MainActivity.this, msg, null);
                }
            }
        });
    }

    // 确认出出出园信息
    private void reqConfirmOut(String id) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id);
        params.put("partition", currPartition.getIndex());

        hideProgress();
        showProgress();
        Gl.okHttp.get().url(Url.OUT_CONFIRM).params(params)
                .tag(this).enqueue(this, new JsonResponseHandler() {
            @Override
            public void onFailure(int statusCode, String error_msg) {
                hideProgress();
                ToastUtils.showShort("请求失败");
                Logg.i("reqConfirmOut.error_msg = " + error_msg);
            }

            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                hideProgress();
                String code = response.optString("code");
                String msg = response.optString("msg");
                String data = response.optString("data");
                Logg.i("reqConfirmOut.code = " + code + " msg = " + msg);
                Logg.i("reqConfirmOut.data = " + data);
                if (TextUtils.equals("1", code)) {
                    AlertUtil.showComDialog2(MainActivity.this, msg, null);
                } else {
                    ToastUtils.showShort(msg);
                    AlertUtil.showComDialog2(MainActivity.this, msg, null);
                }
            }
        });
    }

    // 请求园区列表
    private void reqParkList() {
        Map<String, String> params = new HashMap<>();
//        params.put("id", id);

        hideProgress();
        showProgress();
        Gl.okHttp.get().url(Url.PARK_LIST).params(params)
                .tag(this).enqueue(this, new JsonResponseHandler() {
            @Override
            public void onFailure(int statusCode, String error_msg) {
                hideProgress();
                ToastUtils.showShort("请求失败");
                Logg.i("reqParkList.error_msg = " + error_msg);
            }

            @Override
            public void onSuccess(int statusCode, JSONObject response) {
                hideProgress();
                String code = response.optString("code");
                String msg = response.optString("msg");
                String data = response.optString("data");
                Logg.i("reqParkList.code = " + code + " msg = " + msg);
                Logg.i("reqParkList.data = " + data);
                if (TextUtils.equals("1", code)) {
                    try {
                        partitionList = Gl.gson.fromJson(data, new TypeToken<ArrayList<Partition>>() {
                        }.getType());
                        if (!isDataEmpty(partitionList)) {
                            currPartition = partitionList.get(0);
                            if (null != currPartition) {
                                tv_partition.setText(currPartition.getName());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    ToastUtils.showShort(msg);
                }
            }
        });
    }

    // 弹窗展示入园信息
    private AlertDialog alert;// 弹窗
    private View alert_view;

    public void showDialog(final EnterQuery enter) {// 弹窗
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_enter_query, null);

        TextView tv_content = alert_view.findViewById(R.id.tv_content);
        TextView tv_xc_code = alert_view.findViewById(R.id.tv_xc_code);// 行程码
        TextView tv_hs_report = alert_view.findViewById(R.id.tv_hs_report);// 核酸报告


        if (TextUtils.isEmpty(enter.getTour_code())) {
            tv_xc_code.setVisibility(View.GONE);
        } else {
            tv_xc_code.setVisibility(View.VISIBLE);
        }

        if (TextUtils.isEmpty(enter.getReport())) {
            tv_hs_report.setVisibility(View.GONE);
        } else {
            tv_hs_report.setVisibility(View.VISIBLE);
        }

        String content = "商户名：" + enter.getMerchant() + "\n"
                + "姓名：" + enter.getUsername() + "\n"
                + "联系电话：" + enter.getMobile() + "\n"
                + "家庭地址：" + enter.getAddress() + "\n"
                + "来本地时间：" + enter.getLocal_time() + "\n"
                + "活动地点：" + enter.getActivity_place() + "\n"
                + "车号牌：" + enter.getCar() + "\n"
                + "是否属于重点人群及分类：" + (TextUtils.equals("1", enter.getSpecial()) ? "是" : "否") + "\n"
                + "有无发热咳嗽等症状：" + (TextUtils.equals("1", enter.getHealth()) ? "有" : "无") + "\n"
                + "随行人员：" + enter.getEntourage() + "\n"
                + "填表时间：" + enter.getTbtime() + "\n"
                + "入园时间：" + enter.getRytime() + "\n"
                + "园区：" + Gl.getParkByCode(enter.getPartition());
        tv_content.setText(content);

        alert_view.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert.dismiss();
                cusZxing.cameraResume();// 恢复扫码
                reqConfirmEnter(enter.getId());
            }
        });
        tv_xc_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> imgPaths = new ArrayList<>();
                imgPaths.add(enter.getTour_code());

                Intent intent = new Intent(MainActivity.this, PhotoCheckActivity.class);

                intent.putExtra("position", 0);
                intent.putExtra("list", imgPaths);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });
        tv_hs_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> imgPaths = new ArrayList<>();
                imgPaths.add(enter.getReport());

                Intent intent = new Intent(MainActivity.this, PhotoCheckActivity.class);

                intent.putExtra("position", 0);
                intent.putExtra("list", imgPaths);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });

        AlertUtil.setAlertCenterStyle(alert.getWindow(), alert_view, this);
        alert.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    // 弹窗展示出出出园信息
    private AlertDialog alert2;// 弹窗
    private View alert_view2;

    public void showDialog2(final OutQuery out) {// 弹窗
        alert2.show();
        alert_view2 = View.inflate(this, R.layout.layout_alert_out_query, null);

        TextView tv_content = alert_view2.findViewById(R.id.tv_content);
        TextView tv_hs_report = alert_view2.findViewById(R.id.tv_hs_report);

        if (TextUtils.isEmpty(out.getReport())) {
            tv_hs_report.setVisibility(View.GONE);
        } else {
            tv_hs_report.setVisibility(View.VISIBLE);
        }

        String content = "商户名：" + out.getMerchant() + "\n"
                + "姓名：" + out.getUsername() + "\n"
                + "联系电话：" + out.getMobile() + "\n"
                + "车号牌：" + out.getCar() + "\n"
                + "外发单位：" + out.getOutgoing() + "\n"
                + "疫苗接种情况：" + (TextUtils.equals("1", out.getVaccine()) ? "已接种" : "未接种") + "\n"
                + "随行人员：" + out.getEntourage() + "\n"
                + "填表时间：" + out.getTbtime() + "\n"
                + "出园时间：" + out.getCytime() + "\n"
                + "园区：" + Gl.getParkByCode(out.getPartition());
        tv_content.setText(content);

        alert_view2.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
                cusZxing.cameraResume();// 恢复扫码
                reqConfirmOut(out.getId());
            }
        });
        tv_hs_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> imgPaths = new ArrayList<>();
                imgPaths.add(out.getReport());

                Intent intent = new Intent(MainActivity.this, PhotoCheckActivity.class);

                intent.putExtra("position", 0);
                intent.putExtra("list", imgPaths);
                startActivity(intent);
                overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
            }
        });

        AlertUtil.setAlertCenterStyle(alert2.getWindow(), alert_view2, this);
        alert2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        alert2.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        cusZxing.cameraResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        cusZxing.cameraPause();
    }

    @Override
    public void onBackPressed() {
        // 点击返回什么都不做
    }

}